const express = require('express')
const cors = require('cors')
const app = express()
const query = require('./utils/query.js')
const moment = require('moment')
app.use(cors())
app.use(express.json())
app.use(express.urlencoded({ extended: true }))

// get 获取所有的数据
app.get('/getComment', async (req, res) => {
  // 1. 编写sql语句
  let sql = 'select * from comment'
  // 2. 查询
  let data = await query(sql)
  // 3. 将数据以json格式响应给前端
  res.json(data)
})

// post 提交评论
app.post('/postComment', async (req, res) => {
  // 1. 接收参数
  let { content } = req.body
  // 2. 编写sql语句，执行
  let nowDate = moment().format('YYYY-MM-DD HH:mm:ss')
  let sql = `insert into comment(content,pub_time) values('${content}','${nowDate}')`
  let affectedRows =  await query(sql)
  // 3. 响应数据给前端
  if (affectedRows) {
    res.json({ code: 20000, message: '添加成功' })
  } else {
    res.json({ code: 20001, message: '添加失败' })
  }
})

// get 删除评论
app.delete('/delComment', async (req, res) => {
  let { id } = req.query
  if (!id) {
    res.json({ code: 20002, message: '参数错误，请阅读api文档' })
    return
  }
  let sql = `delete from comment where id = ${id}`
  let { affectedRows } = await query(sql)
  if (affectedRows) {
    res.json({ code: 20000, message: '删除成功'})
  } else {
    res.json({ code: 20001, message: '删除失败' })
  }
})

app.listen(3000, () => {
  console.log('server is running at port 3000')
})
